
local require = require;
local ngx     = ngx;
local pairs   = pairs;
local string  = string;
local collectgarbage = collectgarbage;
local table = table;
local io = io;
local assert = assert;
local tonumber = tonumber;

local log          = require("modules.commhm.log")
local ns_time      = require("modules.commhm.time")
local uu           = require("modules.commhm.utils")
local ns_env       = require("modules.env.env")

local ns_auth_comm_checker    = require("modules.commhm.auth_comm_checker");
local gg                      = require("modules.keeper_server.keeper_gg")


local FOO = {
	_VERSION = '0.12.1',

	operations = {},
};


function FOO.do_command()
	local op_ = ngx.ctx.m_params.op
	if  FOO.operations[ op_ ] then
		FOO.operations[ op_ ]()
	else
		gg.return_table( { ret=99, msg="err_rent_op" } )
	end
end



----数字是CD时间秒
FOO.safe_check_v1 = {
	[ "rsync_node_home" ] = 3,
	[ "rent_node_config0" ] = 3,
	[ "rsync_code" ] = 3,

	[ "rent_node_by_docker_image" ] = 60,
	[ "rent_node_gs0" ] = 60,
	[ "gs0" ] = 60,
};


----执行下面这个脚本，实现多个功能
----/home/install_std_server_env_rent.sh  旧版本 /home/install_std_server_env.sh
---同步所有代码
---同步gs0
function FOO.operations.shell_install()
	if  ngx.ctx.m_params.v1 and (not FOO.safe_check_v1[ ngx.ctx.m_params.v1 ]) then
		gg.return_table( { ret=0, msg="unchecked_v1" } )
		return
	end


	local cd_ = FOO.safe_check_v1[ ngx.ctx.m_params.v1 ]
	---check cd
	if  uu.check_server_time_interval( "node_shell_install", cd_ ) then

		local rent_shell_name_ = "/home/install_std_server_env_rent.sh"
		if  not uu.file_exist( rent_shell_name_ ) then
			rent_shell_name_ = "/home/install_std_server_env.sh"   --旧版本
		end

		local cmd_, msg_
		if  ngx.ctx.m_params.need_return == '1' then
			---直接执行
			cmd_ = rent_shell_name_ .. " " .. (ngx.ctx.m_params.v1 or "")
			msg_ = uu.os_exec_file( cmd_ )
		else
			---后台执行
			cmd_ = "nohup " .. rent_shell_name_ .. " " .. (ngx.ctx.m_params.v1 or "")
			if  cd_ > 10 then
				cmd_ = cmd_ .. " & "
			end
			msg_ = uu.os_exec( cmd_ )  .. " [run in nohup-mod]"
		end

		log.day_list( "keeper", "shell_install", ngx.ctx.m_params.v1, cmd_, msg_ )
		gg.return_table( { ret=0, msg=msg_ } )
	else
		log.day_list( "keeper", "shell_install", ngx.ctx.m_params.v1, "error_cd", cd_ )
		gg.return_table( { ret=1, msg="check_cd_fail" } )
	end

end


----重新 reload rent_node
function FOO.operations.reload_rent_node()
	local cmd_ = "cd /usr/local/openresty/nginx/; /usr/local/openresty/nginx/reload_rent_node.sh;"
	local msg_ = uu.os_exec( cmd_ )
	gg.return_table( { ret=0, msg=msg_ } )
end


return FOO;
